package com.china.lottery.listener.jczq.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JinCaiGrepUtil {

	/**
	 * 通过HTTP获取数据
	 * @param url
	 * @param encoding
	 * @param timeout
	 * @return
	 * @throws Exception
	 */
	public static String fetchDataFromURL(String url,String encoding,int timeout) throws Exception {
		String contents = "";
		ByteArrayOutputStream bout = null;
		HttpURLConnection con = null;

		URL murl = new URL(url);
		con = (HttpURLConnection) murl.openConnection();
		con.setConnectTimeout(1000 * timeout);//10秒的超时
		con.setReadTimeout(1000 * timeout);//读取超时

		bout = new ByteArrayOutputStream();
		InputStream in = con.getInputStream();
		byte[] buf = new byte[9182];

		int bytesRead;
		while ((bytesRead = in.read(buf)) != -1) {
			bout.write(buf, 0, bytesRead);
		}
		contents = new String(bout.toByteArray(), encoding);
		
		if ( in != null ) {
			in.close();
			in = null;
		}

		if ( con != null ) {
			con.disconnect();
			con = null;
		}
		
		if (bout != null) {
			bout.close();
			bout = null;
		}

		return contents;
	}
	
}